package net.caixiaomi.info.base;

import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.BuildConfig;
import net.caixiaomi.info.R;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.ConfigQueryModel;
import net.caixiaomi.info.model.QueryUserNoticeModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.StatusBarUtil;
import net.caixiaomi.info.widgets.DefLoading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import icepick.Icepick;
import retrofit2.Call;


public abstract class BaseActivity extends AppCompatActivity {
    public static int activityActive; //全局变量,表示当前在前台的activity数量
    public static boolean isBackground;

    public DefLoading mLoading;
    @Nullable
    @BindView(R.id.toolbar)
    public Toolbar mToolbar;
    @Nullable
    @BindView(R.id.title)
    TextView mTitle;

    @LayoutRes
    protected abstract int layout();

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Icepick.saveInstanceState(this, outState);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置状态栏文字颜色及图标为深色
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        //设置状态栏文字颜色及图标为浅色
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);


        if (layout() != 0) {
            setContentView(layout());
            ButterKnife.bind(this);
        }
        Icepick.setDebug(BuildConfig.DEBUG);
        if (savedInstanceState != null && !savedInstanceState.isEmpty()) {
            Icepick.restoreInstanceState(this, savedInstanceState);
        }
        setupToolbarAndStatusBar();
        adjustFontScale(getResources().getConfiguration());
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStart() {
        //app 从后台唤醒，进入前台
        activityActive++;
        isBackground = false;//记录当前已经进入后台
        super.onStart();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return true;
    }

    @Override
    protected void onStop() {
        activityActive--;
        if (activityActive == 0) {
            //app 进入后台
            isBackground = true;//记录当前已经进入后台
            loadConfig();
            if (!TextUtils.isEmpty(CommonApp.getToken())) {
                queryUserNotice();
            }
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void setupToolbarAndStatusBar() {
        StatusBarUtil.setStatusBarColor(this, R.color.bar_background_color);
        StatusBarUtil.StatusBarLightMode(this);
        if (mToolbar != null) {
            setSupportActionBar(mToolbar);
            if (getSupportActionBar() != null) {
                getSupportActionBar().setTitle("");
//                getSupportActionBar().setHomeAsUpIndicator();
                mToolbar.setNavigationIcon(R.mipmap.ic_back);
//                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                if (mTitle != null) {
//                    StringBuilder stringBuilder = new StringBuilder();
//                    stringBuilder.append(getString(R.string.app_name));
//                    if (!TextUtils.isEmpty(getTitle())) {
//                        stringBuilder.append(" · ").append(getTitle());
//                    }
//                    mTitle.setText(stringBuilder.toString());

                    mTitle.setText(getTitle());
                }
                mToolbar.setBackgroundResource(R.color.bar_background_color);
            }
        }
        //设置状态栏文字颜色及图标为浅色
        if(getResources().getColor(R.color.bar_background_color)==getResources().getColor(R.color.orange_third_text)){
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }else{
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    public void changeTitle(String title) {
        mTitle.setText(title);
    }

    protected void setToolbarIcon(@DrawableRes int res) {
        if (getSupportActionBar() != null) {
            getSupportActionBar().setHomeAsUpIndicator(res);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @RequiresApi(value = 21)
    protected void changeAppColor() {
        if (AppHelper.isLollipopOrHigher()) {
            getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.background));
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                AppHelper.hideKeyboard(getCurrentFocus());
            }
        }
        return super.onTouchEvent(event);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onPostEvent(CommonEvent event) {
    }

    @Override
    public void onBackPressed() {
        if (getCurrentFocus() != null) {
            AppHelper.hideKeyboard(getCurrentFocus());
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            finishAfterTransition();
        } else {
            finish();
        }
    }

    private void adjustFontScale(Configuration configuration) {
        try {
            if (configuration.fontScale != 1.0) {
                configuration.fontScale = (float) 1.0;
                DisplayMetrics metrics = getResources().getDisplayMetrics();
                WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
                wm.getDefaultDisplay().getMetrics(metrics);
                metrics.scaledDensity = configuration.fontScale * metrics.density;
                getResources().updateConfiguration(configuration, metrics);
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//                    getBaseContext().createConfigurationContext(configuration);
//                } else {
//                    getBaseContext().getResources().updateConfiguration(configuration, metrics);
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        adjustFontScale(newConfig);
        super.onConfigurationChanged(newConfig);
    }

    private void loadConfig() {
        JSONObject params = new JSONObject();
        params.put("str", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<ConfigQueryModel>> configQuery = requestService.configQuery(params);
        configQuery.enqueue(new ResponseCallback<BaseCallModel<ConfigQueryModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<ConfigQueryModel> data) {
                ConfigQueryModel model = data.data;
                boolean oldVersion = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);
                boolean newVersion = TextUtils.equals(model.getTurnOn(), "1");
                CommonApp.STORE.set(Constants.KEY_DEAL_VERSION, newVersion);
                if (oldVersion != newVersion) {
                    EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_APP_BACKGROUND_UPDATE_DEAL_VERSION));
                }
            }

            @Override
            public void onFail(ResponseError error) {
                if (error.getCode() == 301030) {
                    CommonApp.STORE.set(Constants.KEY_DEAL_VERSION, false);
                }
            }

            @Override
            public void onError() {
            }
        });
    }

    private void queryUserNotice() {
        JSONObject params = new JSONObject();
        params.put("str", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<QueryUserNoticeModel>> baseCallModelCall = requestService.queryUserNotice(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<QueryUserNoticeModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<QueryUserNoticeModel> data) {
                QueryUserNoticeModel model = data.data;
                boolean oldMessageNotice = CommonApp.STORE.getBoolean(Constants.KEY_MESSAGE_NOTICE, false);
                boolean oldBonusNotice = CommonApp.STORE.getBoolean(Constants.KEY_BONUS_NOTICE, false);
                boolean newMessageNotice = model.getMessageNotice() != 0;
                boolean newBonusNotice = model.getBonusNotice() != 0;
                CommonApp.STORE.set(Constants.KEY_MESSAGE_NOTICE, newMessageNotice);
                CommonApp.STORE.set(Constants.KEY_BONUS_NOTICE, newBonusNotice);
                if (oldMessageNotice != newMessageNotice || oldBonusNotice != newBonusNotice) {
                    EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_NEW_NOTICE_POINT));
                }

            }

            @Override
            public void onFail(ResponseError error) {
            }

            @Override
            public void onError() {
            }
        });
    }

}
